import 'package:dio/dio.dart';
import 'dart:convert' as convert;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:graduation_project/books/cartoon_leader_mod/user_evaluation.dart';
import 'package:graduation_project/books/cartoon_page_mod/allpage.dart';
import 'package:graduation_project/common/StaticRatingBar.dart';
import 'package:graduation_project/found/found_six_mod.dart';

import 'cartoon_page_value.dart';
import 'cartoon_leader_mod/more_recommend.dart';

class cartoon_leader extends StatefulWidget {
  cartoon_leader({Key key, this.cartoon_id}) : super(key: key);
  int cartoon_id = 1;
  @override
  State<cartoon_leader> createState() => _cartoon_leaderState();
}

class _cartoon_leaderState extends State<cartoon_leader> {
  // ScrollController _scrollController = new ScrollController();
  ScrollController _scrollC_page = new ScrollController();

  int sort = 0;
  // double op = 0;

  String cartton_name = '间谍过家家';
  String top_image_url = 'http://www.itying.com/images/flutter/1.png';
  int collect = 0;
  String author = '远藤达哉';
  String tage = '都市';
  int stae = 0;
  double grade = 9.0;
  // 当前看的话数
  int read_page = 1;
  // 总共的话数
  int cartoon_page = 76;
  List cartoonPartList = [];
  List title_num = [];
  String turnover_time = '隔周一更新';
  String brief =
      '       为了潜入名校，西国能力最强的间谍<黄昏>被下令组建家庭.但是，他的“女儿”“居然是能够读取他人内心的超能力者!“妻子”是暗杀者?互相隐藏了真实身份的新家庭，面临考验与世界危机的痛快家庭喜剧就此展开! !';

  // SELECT `cartoon`.`cartoon_name`, `cartoon`.`cartoon_state`, `cartoon`.`cartoon_brief`, `cartoon`.`cartoon_author`, `cartoon`.`cartoon_turnover_time`, `cartoon`.`read_pattern`, `cartoon`.`cartoon_leader_image` FROM `cartoon` WHERE (`cartoon`.` cartoon_id` =1)
  Future _future;
  @override
  void initState() {
    _future = _getinformation();
    // TODO: implement initState
    for (var i = 1; i <= cartoon_page; i++) {
      title_num.add(i);
    }
    _scrollC_page.addListener(() {
      setState(() {});
    });
    super.initState();
  }

  _setCollect() async {
    Response response;
    var dio = Dio();
    response = await dio.get(
        'http://119.91.231.198:3033/insertCollect?cartoon_id=' +
            widget.cartoon_id.toString() +
            '');
  }

  _delCollect() async {
    Response response;
    var dio = Dio();
    response = await dio.get(
        'http://119.91.231.198:3033/delCollect?cartoon_id=' +
            widget.cartoon_id.toString() +
            '');
  }

  _getinformation() async {
    print('异步调用');
    Response response;
    var dio = Dio();
    response = await dio.get(
        'http://119.91.231.198:3033/getCartoonValue?cartoon_id=' +
            widget.cartoon_id.toString() +
            '');

    // page_url0 = response.data['url_list'].cast<String>();
    var res = convert.jsonDecode(response.toString());
    // print(res['resValue']['cartoon_name']);
    cartton_name = res['resValue']['cartoon_name'].toString();
    top_image_url = res['resValue']['cartoon_leader_image'].toString();
    collect = res['resValue']['collect'];
    author = res['resValue']['cartoon_author'];
    stae = res['resValue']['cartoon_state'];
    turnover_time = res['resValue']['cartoon_turnover_time'];
    brief = res['resValue']['cartoon_brief'];
    cartoon_page = res['resValue']['cartoon_page'];
    await _getCartoonPartList();
  }

  _getCartoonPartList() async {
    // http://119.91.231.198:3033/getCartoonPartList?cartoon_id=1
    Response response;
    var dio = Dio();
    response = await dio
        .get("http://119.91.231.198:3033/getCartoonPartList?cartoon_id=1");
    var res = convert.jsonDecode(response.toString());
    cartoonPartList.addAll(res['result']);
    // print(cartoonPartList.length);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    // controller.stop();
    // 离开时关闭
    _scrollC_page.dispose();
    // _scrollController.dispose();
    print('离开分类');
    super.dispose();
  }

  Wrap re_page() {
    return Wrap(
      spacing: 8,
      children: cartoonPartList.asMap().keys.map(((e) {
        return InkWell(
          onTap: () {
            print(e);
          },
          child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 8),
            height: 35,
            width: 50,
            color: e == read_page
                ? Color.fromRGBO(233, 246, 254, 1)
                : Color.fromRGBO(244, 245, 247, 1),
            child: Text(
              (e + 1).toString(),
              style: TextStyle(
                color: e == read_page ? Color.fromRGBO(50, 169, 255, 1) : null,
              ),
            ),
          ),
        );
      })).toList(),
    );
    // print(num);
  }

  @override
  Widget build(BuildContext context) {
    // re_page();
    return FutureBuilder(
      future: _future,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return Scaffold(
            body: NestedScrollView(
              // controller: _scrollController,
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                return <Widget>[
                  SliverAppBar(
                    // leading: null,
                    iconTheme: IconThemeData(color: Colors.black87),
                    automaticallyImplyLeading: true,
                    backgroundColor: Colors.white,
                    expandedHeight: 460.0,
                    pinned: true,
                    floating: true,
                    snap: false,
                    // ignore: missing_return
                    title: Text(
                      cartton_name,
                      style: TextStyle(color: Colors.black87),
                    ),
                    flexibleSpace: new FlexibleSpaceBar(
                        background: Image(
                            fit: BoxFit.fill, image: NetworkImage(top_image_url)
                            // http://www.itying.com/images/flutter/1.png
                            )),
                    actions: [
                      Container(
                        margin: EdgeInsets.only(top: 0, right: 0),
                        child: Image.asset(
                            'assets/images/common/cartoon/down.png'),
                      ),
                    ],
                  ),
                ];
              },
              body: ListView.builder(
                  // controller: _scrollController,
                  itemCount: 1,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      // padding: EdgeInsets.a,

                      margin: EdgeInsets.only(top: 0),
                      // height: 900,
                      color: Colors.white,
                      child: Column(children: [
                        Row(children: [
                          Container(
                              margin: EdgeInsets.only(left: 14),
                              child: Text(
                                cartton_name,
                                style: TextStyle(fontSize: 20),
                              )),
                          Expanded(child: SizedBox()),
                          Container(
                            // padding: EdgeInsets.all(4),
                            margin: EdgeInsets.only(right: 16),
                            // ignore: deprecated_member_use
                            child: RaisedButton(
                              color: collect == 0
                                  ? Colors.amber[700]
                                  : Colors.black12,
                              onPressed: () {
                                setState(() {
                                  if (collect == 0) {
                                    _setCollect();
                                    collect = 1;
                                  } else {
                                    _delCollect();
                                    collect = 0;
                                  }
                                });
                                // print('追漫');
                              },
                              shape: BeveledRectangleBorder(
                                // side: BorderSide(width: 1, color: Colors.red),
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(10),
                                    bottomRight: Radius.circular(10)),
                              ),
                              child: Row(
                                children: [
                                  Container(
                                    margin: EdgeInsets.only(top: 0, right: 4),
                                    child: Image.asset(
                                      'assets/images/common/cartoon/shoucang.png',
                                      // color: Colors.black26,
                                    ),
                                  ),
                                  Container(
                                    child: Text(
                                      collect == 0 ? '追漫' : '已追',
                                      style: TextStyle(
                                          fontSize: 16, color: Colors.white),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ]),
                        Row(children: [
                          Container(
                            alignment: Alignment.topLeft,
                            width: 105,
                            color: Color.fromRGBO(245, 246, 248, 1),
                            // padding: EdgeInsets.only(left: 2),
                            margin: EdgeInsets.only(left: 12),
                            child: Row(children: [
                              Container(
                                margin: EdgeInsets.only(left: 4),
                                child: Text(
                                  grade.toString(),
                                  style: TextStyle(fontSize: 10),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 2),
                                child: StaticRatingBar(
                                  size: 12.0,
                                  rate: grade / 2,
                                ),
                              ),
                              Icon(
                                Icons.chevron_right,
                                color: Colors.black26,
                              )
                            ]),
                          ),
                        ]),
                        Container(
                          margin: EdgeInsets.only(left: 12, top: 8),
                          child: Row(
                            children: [
                              Text(
                                stae == 0 ? '连载中 ' : '已完结 ',
                                style: TextStyle(fontSize: 12),
                              ),
                              Text(
                                turnover_time,
                                style: TextStyle(fontSize: 12),
                              )
                            ],
                          ),
                        ),
                        // 点击出现的简介
                        Container(
                          child: ExpansionTile(
                            title: Row(children: [
                              Text(
                                '作者：' +
                                    author +
                                    '·' +
                                    tage +
                                    '丨' +
                                    ((stae == 0) ? '已更新' : '已完结') +
                                    cartoon_page.toString() +
                                    '话',
                                style: TextStyle(
                                    color: Colors.black54, fontSize: 10),
                              ),
                              Expanded(child: SizedBox()),
                              Text(
                                '查看简介',
                                style: TextStyle(
                                    color: Colors.black54, fontSize: 10),
                              )
                            ]),
                            // 放开始的组件

                            // 设置点开后的背景颜色
                            backgroundColor: Colors.white24,
                            // 设置展开显示的内容
                            children: <Widget>[
                              Container(
                                  // height: 60,
                                  alignment: Alignment.topLeft,
                                  margin: EdgeInsets.only(left: 10),
                                  child: Text(
                                    '简介：',
                                    style: TextStyle(
                                        color: Colors.black54, fontSize: 10),
                                  )),
                              Container(
                                  margin: EdgeInsets.only(bottom: 10),
                                  width: 310,
                                  child: Text(
                                    brief,
                                    style: TextStyle(
                                        color: Colors.black54, fontSize: 12),
                                  )),
                            ],
                            // 第一次显示打开的状态
                            //initiallyExpanded: true,
                          ),
                        ),
                        // 简介结束
                        Row(children: [
                          Container(
                            margin: EdgeInsets.only(left: 10),
                            // alignment: Alignment.topLeft,
                            child: Text('漫画点评'),
                          ),
                          Expanded(child: SizedBox()),
                          InkWell(
                            onTap: () {
                              print('查看全部');
                            },
                            child: Row(children: [
                              Container(
                                child: Text(
                                  '查看全部',
                                  style: TextStyle(
                                      color: Colors.black54, fontSize: 12),
                                ),
                              ),
                              Container(
                                  margin: EdgeInsets.only(right: 12),
                                  child: Icon(
                                    Icons.chevron_right,
                                    size: 18,
                                    color: Colors.black54,
                                  )),
                            ]),
                          )
                        ]),
                        user_evaluation_mode(),
                        user_evaluation_mode(),
                        // found_six_mod(title_id: 1007),
                        more_recommend(
                          recommend_id: 1008,
                        )
                      ]),
                    );
                  }),
            ),
            persistentFooterButtons: [
              InkWell(
                onTap: () {
                  showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                        return allpage(
                          partnum: (value) {
                            Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => cartoon_page_value(
                                          cartoon_id: widget.cartoon_id,
                                          page: value,
                                          allNum: cartoonPartList.length,
                                        )));
                          },
                        );
                      });
                },
                child: Container(
                  height: 50,
                  width: MediaQuery.of(context).size.width * 0.1,
                  padding: EdgeInsets.only(top: 2),
                  // color: Colors.green,
                  child: Column(
                    children: [
                      Icon(
                        Icons.library_books_rounded,
                        color: Colors.black54,
                      ),
                      Text(
                        '目录',
                        style: TextStyle(color: Colors.black54),
                      )
                    ],
                  ),
                ),
              ),
              // Expanded(child: SizedBox()),
              Container(
                height: 50,
                width: MediaQuery.of(context).size.width * 0.6,
                // color: Colors.green,
                constraints: BoxConstraints(maxWidth: 500),
                child: Stack(
                  children: [
                    ListView(
                      controller: _scrollC_page,
                      // This next line does the trick.
                      scrollDirection: Axis.horizontal,
                      children: <Widget>[
                        // pageList,
                        re_page(),
                      ],
                    )
                  ],
                ),
              ),
              InkWell(
                onTap: () {
                  print('续看');
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => cartoon_page_value(
                                cartoon_id: widget.cartoon_id,
                                page: read_page,
                                allNum: cartoonPartList.length,
                              )));
                  // cartoon_page_value
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50,
                  width: MediaQuery.of(context).size.width * 0.2,
                  color: Color.fromRGBO(49, 170, 255, 1),
                  child: Text(
                    '续看' + read_page.toString() + '话',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          );
        } else {
          return Container();
        }
      },
    );
  }
}
